﻿using KinonekoSoftware.CodariaDB.Presets;

namespace KinonekoSoftware.CodariaDB.Core
{
    public sealed class GravatarSystem : _File
    {
        public GravatarSystem() : base("Avatars", ResourceType.Avatar)
        {

        }

        public bool Exists(string id,  out string fileName)
        {
            fileName = Path.Combine(Folder, string.Format(ImageFilePattern, id));
            return File.Exists(fileName);
        }
        
        
        protected override Occupation OnCreate(string id) => new Occupation
        {
            Id       = id,
            FileName = id,
            Usage    = true,
            Type     = ResourceType.Avatar,
        };

        #region GetPresetAvatar

        
        public static byte[] GetPresetAvatar(Preset_Avatar avatar)
        {
            if (avatar == Preset_Avatar.Override)
                avatar = Preset_Avatar.Avatar_4;

            var index    = (int)avatar;
            var name     = $"{PresetManager.FileName_Prefix}{PresetManager.FileName_Avatar[index]}";
            var assembly = typeof(PresetManager).Assembly;

            var r = PresetManager.ExtractResourceToBuffer(assembly, name);

            if (!r.IsFinished)
            {
                return Array.Empty<byte>();
            }

            return r.Value;
        }
        

        #endregion

        #region GetPresetAvatarFilePath

        
        public static string GetPresetAvatarFilePath(string workspace)
        { 
            var presets = GetDir(null, Path.Combine(workspace, "Presets"));
            return Path.Combine(presets,"avatar.png");
        }
        
        
        public string GetPresetAvatarFilePath()
        { 
            var presets = GetDir(null, Path.Combine(Workspace, "Presets"));
            return Path.Combine(presets,"avatar.png");
        }

        #endregion

        #region OverrideAvatar

        
        public static async Task OverrideAvatar(string workspace, byte[] buffer)
        {
            await File.WriteAllBytesAsync(GetPresetAvatarFilePath(workspace), buffer);
        }
        
        
        public async Task OverrideAvatar(byte[] buffer)
        {
            await File.WriteAllBytesAsync(GetPresetAvatarFilePath(Workspace), buffer);
        }

        #endregion

        public override string EngineID => EngineNames.FileDataSet_Gravatar;
    }
}